package com.mobileagri.backoffice.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.mobileagri.backoffice.model.AbstractObject;
import com.mobileagri.backoffice.model.Message;

/**
 * 
 * @author LOUVET Romain
 * @param <E>
 * 
 */
@Repository
public class MessageDAO<E> extends AbstractDAO implements IDAO {

	private HibernateTemplate hibernateTemplate;

	private SessionFactory sessionFactory;

	/**
	 * Get List of Message from database
	 * 
	 * @return list of all Message
	 */
	public List<Message> getAll(int start, int limit) {

		List<Message> listMessage = new ArrayList<Message>();
		List<Object> listObject = super.getObjects(new Message(), start, limit);
		for (Object o : listObject) {
			listMessage.add((Message) o);
		}

		return listMessage;
	}

	/**
	 * Get List of Message from database
	 * 
	 * @return list of all Message
	 */
	public List<Message> getAll(int start, int limit, String sort) {

		List<Message> listMessage = new ArrayList<Message>();
		List<Object> listObject = super.getObjects(new Message(), start, limit,
				sort);
		for (Object o : listObject) {
			listMessage.add((Message) o);
		}

		return listMessage;
	}

	/**
	 * Get List of contacts from database
	 * 
	 * @return list of all contacts
	 */
	@SuppressWarnings("unchecked")
	public List<E> getAll() {
		String sqlQuery = " from Message";

		getHibernateTemplate().find(sqlQuery);
		return (List<E>) getHibernateTemplate().find(sqlQuery);
	}

	/**
	 * Delete a contact with the id passed as parameter
	 * 
	 * @param id
	 */
	public void delete(int id) {
		super.delete(new Message(), id);
	}

	/**
	 * Create a new Contact on the database or Update contact
	 * 
	 * @param contact
	 * @return contact added or updated in DB
	 */
	public AbstractObject save(AbstractObject o) {
		Message message = (Message) o;
		return (Message) super.save(message);
	}

	/**
	 * Get total of Message from database
	 * 
	 * @return
	 */
	public int getTotal() {
		return DataAccessUtils.intResult(getHibernateTemplate().find(
				"SELECT COUNT(*) FROM Message"));
	}

}
